package com.gxa.medical.controller;

import com.alipay.service.schema.util.StringUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.medical.exception.BusinessException;
import com.gxa.medical.exception.ExceptionCode;
import com.gxa.medical.util.JsonResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
@RestController
public class SMSController {
    private JsonResult jsonResult = new JsonResult();
    @RequestMapping("/sms")
    public Map<String,Object> doSend(HttpServletRequest req) throws Exception {
        // 从参数中获取手机号
        String phone = req.getParameter("phone");
        // 确保手机号非空
        if (!StringUtil.isEmpty(phone)) {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tGSEWzS9RM8EjC2w8bK", "IaTDtee5wde5RLvl3qIEXBZxbcMPOm");
            IAcsClient client = new DefaultAcsClient(profile);
            // 配置发送参数
            CommonRequest request = new CommonRequest();
            // 标准的服务器参数, 不能改
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            // 填写接收短信的手机号
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", "小溪商城");
            request.putQueryParameter("TemplateCode", "SMS_204986028");
            // 生成4位随机数
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 4; i++) {
                builder.append(new Random().nextInt(8) + 1);
            }
            // 把验证码记录到session中
            HttpSession session = req.getSession();
            // 把验证码添加到session中
            session.setAttribute("captcha", builder.toString());
            // 把手机号添加session中
//                session.setAttribute("phone",phone);
            // 作弊方式获取session存的验证码
            System.out.println("captcha:" + builder.toString());
            // 给阿里云短信模板中的${code}赋值，json格式
            request.putQueryParameter("TemplateParam", "{'code':" + builder.toString() + "}");
            try {
                // 执行发送操作
                CommonResponse response = client.getCommonResponse(request);
                // 获取 阿里短信接口给当前的发送请求响应的数据
                String data = response.getData();
                //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> tmpMap = mapper.readValue(data, Map.class);
                // Code 为OK表示发送成功
                if ("OK".equals(tmpMap.get("Code"))) {
                    // 给前端返回消息, 发送成功
                    jsonResult.setCode("ok");
                    return jsonResult.getResultMap();
                } else {
                    throw new BusinessException(ExceptionCode.SEND_SMS_FAILED);
                }

            } catch (Exception e) {
                throw new BusinessException(ExceptionCode.SEND_SMS_FAILED);
            }


        } else {
            // 当手机号不符合规则, 创建一个自定义异常(手机号格式不正确)
            // 传给统一异常处理器集中处理
            throw new BusinessException(ExceptionCode.WRONG_PHONE_NUMBER);

        }
    }

}
